﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;


namespace OrderConsoleApplication
{
    public  class Server
    {
        Thread th = null;
        private TcpClient _client;
        private NetworkStream _networkStream;
        private byte[] _byteBuffer;
        private const int BYTE_BUFFER_SIZE = 1024;
        public Server(TcpClient client)
        {
            this._client = client;
            Console.WriteLine("Client Connected! local:{0}<---Client:{1}", client.Client.LocalEndPoint, client.Client.RemoteEndPoint);
            _networkStream = client.GetStream();
            _byteBuffer = new byte[BYTE_BUFFER_SIZE];
            _networkStream.BeginRead(_byteBuffer, 0, BYTE_BUFFER_SIZE, ReadAsyncCallback, this);
        }

        public void ReadAsyncCallback(IAsyncResult ar)
        {
            int bytesRead = 0;
            try
            {
                bytesRead = _networkStream.EndRead(ar);
                if (bytesRead == 0)
                {
                    Console.WriteLine("Client offline");
                    return;
                }
                string msg = Encoding.Unicode.GetString(_byteBuffer, 0, bytesRead);
                Array.Clear(_byteBuffer, 0, _byteBuffer.Length);
                Console.WriteLine("Received Client Message : {0}", msg);



                int s =  60;
                string parms = s + "," + msg;
                th = new Thread(new ParameterizedThreadStart(method));
                th.Start(parms);


                //向客户端发送数据
                //string callBackMsg = String.Format("Server Received Message :{0} .", msg);
                //byte[] byteBuffer = Encoding.Unicode.GetBytes(callBackMsg);
                //_networkStream.Write(byteBuffer, 0, byteBuffer.Length);
                ////再次调用BeginRead(),完成自身调用，形成无限循环
                //_networkStream.BeginRead(_byteBuffer, 0, BYTE_BUFFER_SIZE, ReadAsyncCallback, this);
            }
            catch (Exception ex)
            {
                if (_networkStream != null)
                    _networkStream.Dispose();
                _client.Close();
                Console.WriteLine(ex.Message);
            }
        }

        private void method(object parms)
        {
            try
            {
                string[] arr = parms.ToString().Split(',');
                if (arr.Length > 0)
                {
                    int s = Convert.ToInt32(arr[0]);
                    Console.WriteLine("收到订单{0}消息{1}", arr[1].ToString(), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    for (int i = 0; i < s; i++)
                    {
                        var m = GetSingleOrderModel(Convert.ToInt32(arr[1]));
                        if (m!=null)
                        {
                            if (i == (s - 1))
                            {


                                changesql(Convert.ToInt32(arr[1]));
                                string str = "移除订单号|" + arr[1];
                                Console.WriteLine(arr[1].ToString() + "时间到了！");

                                break;



                            }

                          
                        }
                        else
                        {
                     
                            Console.WriteLine(arr[1].ToString() + "状态已经改变！");
                            break;
                        }


                        //Console.WriteLine(i.ToString());
                        Thread.Sleep(1000);

                    }
                }


            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.ToString());
              
            }

        }


        static string str = "server=.;database=BusinessDB;uid=sa;pwd=sa";



        public Model.tb_order GetSingleOrderModel(int no)
        {
            Model.tb_order m = null;
            SqlConnection conn = new SqlConnection(str);
            conn.Open();
            SqlDataAdapter myDataAdapter = new SqlDataAdapter("select * from tb_order where Id=" + no + " and status=1", conn);
            DataSet myDataSet = new DataSet();
            myDataAdapter.Fill(myDataSet);

            DataTable myTable = myDataSet.Tables[0];
            if (myTable.Rows.Count>0)
            {
                DataRow dr = myTable.Rows[0];
                m = new Model.tb_order();
                m.Id = Convert.ToInt32(dr["Id"]);
                m.status = Convert.ToInt32(dr["status"]);
            }
    
            conn.Close();

            return m;
        }
        public static void changesql(int OId)
        {

            SqlConnection conn = new SqlConnection(str);
            conn.Open();
            SqlCommand command = new SqlCommand();
            command.Connection = conn;
            command.CommandType = CommandType.Text;
            command.CommandText = "update tb_order set status=7 where Id=" + OId + "";
            command.ExecuteNonQuery();
            conn.Close();
        }
    }
}
